
require('./tuoguan.scss');

var PaginationX = require("COMMON/modules/pagination-x/v1.0/");

var loading = require('COMMON/js/util.loading.pc.js');

var Toast = require('COMMON/modules/Toast');
var toast = new Toast;

var ParseTemplate = ZFT.Util.ParseTemplate;
var Template = {
    tr: ParseTemplate(require("./tpl/mycontract_tr.xtpl")),
    rule: ParseTemplate(require("./tpl/mycontract_rule.xtpl")),
    ruleEditable: ParseTemplate(require("./tpl/mycontract_rule_edit.xtpl")),
    opermodal: ParseTemplate(require("./tpl/orperatemodal.xtpl"))
};

var DataProvinceCity = require('COMMON/Components/ProvCitySelect/province.city.data.js');

var Main = ZFT.Util.Class({
    container: "body",

    ruleInited: false,

    dom: {
        tbodyMyct: '#tbodyMyct',
        pagination: $(".paginationWrap"),
        rule: {
            container: '#rule',
            tbody: '#tbodyRuleEdit',
            btn: {
                add: '#btnAddRatio',
                edit: '#btnEditRule'
            },
            input: {
                rate: '#inpRate',
                ratio: '#inpRatio'
            },
            settle_type: '#settleType',
            money: '#money',
            begin_time: '#beginDate',
            end_time: '#endDate',
            billing_day: '#billingDay'
        }
    },

    xhrGetRule: null,
    xhrGetContracts: null,
    init: function () {
        var _this = this;

        this.params = {
            page: 1,
            page_size: 15
        };

        this.ajaxGetContracts(this.params);

        $(this.dom.tbodyMyct).on('click', '.btn-getrule', function (e) {

            var id = $(e.target).attr('data-id'),
                status = $(e.target).attr('data-status');

            _this.ajaxGetRule(id, status);
        }).on('click', '.invCt', function (e) {
            _this.onpenInvModal(e);
        });
        $("body").on('click', '.cancel,.close', function (e) {
            _this.closeModal(e);
        })
        $(this.dom.rule.container).on('click', this.dom.rule.btn.add, function () {
            var rate = $.trim($(_this.dom.rule.input.rate).val()),
                ratio = $.trim($(_this.dom.rule.input.ratio).val()),
                r = /^[0-9]{1,2}$/,
                rateArr = $(_this.dom.rule.tbody).find('td:first-child').children('input').map(function () { return this.value; }).get();

            if ((r.test(rate) || rate == 100) && (r.test(ratio) || ratio == 100) && rateArr.indexOf(rate) == -1) {
                $(_this.dom.rule.tbody).append('<tr><td><input class="input t-center" value="' + rate + '"> %</td><td><input class="input t-center" value="' + ratio + '"> %</td></tr>');
            } else {
                ZFT.Util.STip("fail", "出租率不能与现有相同,并且分成比例不超过100", 5000);
            }
        }).on('click', this.dom.rule.btn.edit, function () {
            var houseInfo = {
                settlenum: $(this).attr('data-id'),
                owner_id: $(this).attr('data-ownerid')
            };
            _this.ajaxSaveRule(houseInfo);

        });

    },
    ajaxRenderData: function (opts) {
        return ZFT.Util.Ajax(opts.url, {
            type: 'POST',
            params: opts.params,
            loading: function () {
                var loadingOpts = {};

                loadingOpts.id = opts.loading.id;
                loadingOpts.text = opts.loading.text || '';
                loadingOpts.className = opts.loading.className;
                loadingOpts.tag = opts.loading.tag || '';
                if (opts.loading.tag == 'td' || opts.loading.tag == 'tr') {
                    loadingOpts.colspan = opts.loading.colspan ? opts.loading.colspan : '';
                }

                var html = loading(opts.loading.text, loadingOpts);
                $(opts.container).html(html);
            },
            success: function (res) {
                $('#' + opts.loading.id).remove();


                if (res.code == 200 || res.code == 'success') {
                    opts.success && opts.success(res);
                } else {

                    opts.error && opts.error(res);
                }
            },
            serverError: function (xhr, txt) {

            }
        })
    },

    ajaxSendData: function (opts) {
        /*
            opts: {
                url:
                params:
                loading: {
                    text
                }
                success: fn
            }
         */
        return ZFT.Util.Ajax(opts.url, {
            type: 'POST',
            params: opts.params,
            loading: function () {
                toast.show('loading', opts.loading.text);
            },
            success: function (res) {
                toast.hide();

                if (res.code == 200) {
                    opts.success && opts.success(res);
                } else {
                    ZFT.Util.STip('fail', res.msg);
                    opts.error && opts.error(res);
                }
            },
            serverError: function (xhr, txt) {

            }
        })
    },

    ajaxGetContracts: function (params) {
        var _this = this;

        this.xhrGetContracts = this.ajaxRenderData({
            container: this.dom.tbodyMyct,
            url: '/r/Trust_getMyOrder',
            params: params,
            loading: {
                id: 'contractLoading',
                text: '正在努力加载您的合同...',
                className: 'tb-loading',
                colspan: 10,
                tag: 'td'
            },
            success: function (res) {
                _this.renderContractList(res.data.list);

                if (_this.pagination) {

                    _this.pagination.render({ current: res.data.current_page, total: res.data.total });

                } else {

                    _this.pagination = new PaginationX({
                        container: _this.dom.pagination,
                        count: 7,
                        showTotal: true,
                        jump: true,
                        filter: true
                    });

                    _this.pagination.on("page.switch", function (toPage, current, total) {
                        var page_size = $(".paginationWrap").attr("data-size");
                        _this.params.page = toPage;
                        _this.params.page_size = page_size ? page_size : 15;
                        _this.ajaxGetContracts(_this.params);

                    });

                    _this.pagination.render({ current: res.data.current_page, total: res.data.total });

                }
            },
            error: function (res) {
                $(_this.dom.tbodyMyct).html('<tr><td colspan="10" align="center" class="tb-nodata">' + res.msg + '</td></tr>');
            }
        });
    },

    renderContractList: function (data) {
        var tempProv,
            temCity,
            html,
            citys;
        for (var i = 0, len = data.length; i < len; i++) {
            tempProv = DataProvinceCity[data[i].province].name;
            citys = DataProvinceCity[data[i].province].city;

            for (var j = 0, citylen = citys.length; j < citylen; j++) {
                if (data[i].city == citys[j].id) {
                    temCity = citys[j].name;
                    break;
                }
            }
            data[i].province = tempProv;
            data[i].city = temCity;
        }

        // console.log( data );
        var dtype = ZFT.Util.getDtype(),
            pers=ZFT.Util.getPermission();
        data["dtype"] = dtype;
        data["unsetBtn"]=($.inArray("39",pers)!==-1) ? 1 : 0;
        html = Template.tr({ data: data });
        $(this.dom.tbodyMyct).html(html);
    },

    ajaxGetRule: function (id, status) {
        var _this = this;

        this.xhrGetRule = this.ajaxRenderData({
            container: this.dom.rule.container,
            url: '/r/Trust_getOrderDetail',
            params: {
                settlenum: id
            },
            loading: {
                id: 'ruleLoading',
                text: '正在努力加载您的托管结算规则...',
                className: 'rule-loading',
                tag: 'div'
            },
            success: function (res) {
                _this.renderRule(res.data, status);
            },
            error: function (res) {
                $(_this.dom.rule.container).html(res.msg);
            }
        })
    },

    renderRule: function (data, status) {
        var html,
            begin_cycle = data.begin_cycle,
            end_cycle = data.end_cycle;

        if (status == 1) {
            html = Template.rule({ data: data });
        } else {

            html = Template.ruleEditable({ data: data });
        }

        $(this.dom.rule.container).html(html);

        if (!this.ruleInited) {
            $('#beginDate').datepicker({
                format: "yyyymmdd",
                maxViewMode: 2,
                language: "zh-CN",
                autoclose: true
            });

            $('#endDate').datepicker({
                format: "yyyymmdd",
                maxViewMode: 2,
                language: "zh-CN",
                autoclose: true
            });

            this.ruleInited = true;
        }

        // defaultViewDate: { year: end_cycle.substr(0,4), month: end_cycle.substr(4,2), day: end_cycle.substr(6,2) }
    },

    ajaxSaveRule: function (houseInfo) {
        var ruleParams = {};

        ruleParams.rate_arr = $(this.dom.rule.tbody).children('tr').map(function () {
            var rental = $(this).find('input').eq(0).val(),
                split = $(this).find('input').eq(1).val();
            return {
                rental: rental,
                split: split
            }
        }).get();
        ruleParams.settle_type = $(this.dom.rule.settle_type).val();
        ruleParams.money = $(this.dom.rule.money).val();
        ruleParams.begin_time = $(this.dom.rule.begin_time).val();
        ruleParams.end_time = $(this.dom.rule.end_time).val();
        ruleParams.billing_day = $.trim($(this.dom.rule.billing_day).val());


        if (!ruleParams.rate_arr.length) {
            ZFT.Util.STip('fail', '输入出租率/业主分成比例后务必点击添加按钮');
            return false;
        }
        if ($.trim(ruleParams.money) == '') {
            ZFT.Util.STip('fail', '保底金额不能为空');
            return false;
        }
        if ($.trim(ruleParams.begin_time) == '') {
            ZFT.Util.STip('fail', '请选择托管起始日期');
            return false;
        }
        if ($.trim(ruleParams.end_time) == '') {
            ZFT.Util.STip('fail', '请选择托管截止日期');
            return false;
        }
        if (ruleParams.billing_day == '' || parseInt(ruleParams.billing_day) <= 0 || parseInt(ruleParams.billing_day) > 31) {
            ZFT.Util.STip('fail', '账单日输入有误');
            return false;
        }

        var param = $.extend({}, ruleParams, houseInfo);

        // param.house = param.house.join();
        param.rate_arr = JSON.stringify(param.rate_arr);

        //  console.log(param)

        this.xhrSaveContract = this.ajaxSendData({
            url: '/r/Trust_setTrust',
            params: param,
            loading: {
                text: '保存规则...'
            },
            success: function (res) {
                // type,content,duration,callback
                toast.show('success', res.msg, 2000, function () {
                    //  console.log('跳转写这边');
                });
            },
            error: function (res) {

            }
        })
    },
    //打开失效合同模态框
    onpenInvModal: function (e) {
        var _this = this;
        var tarBtn = $(e.currentTarget);
        var orderid = tarBtn.attr("data-orderid");
        var html = Template.opermodal();
        $("#modal").html(html);
        $(".u-modal-btn_conf").on("click", function () {
            ZFT.Util.Ajax("/r/Trust_forbidTrust", {
                type: "POST",
                dataType: "json",
                params: {
                    orderid: orderid,
                    status: 0
                },
                success: function (res) {
                    if (res.code == 200) {
                        $("#modal").html("");
                        _this.ajaxGetContracts(_this.params);
                        ZFT.Util.STip("success", res.msg, 4000);
                    } else {
                        ZFT.Util.STip("fail", res.msg, 4000);
                    }
                }
            })
        })
    },
    //关闭模态框
    closeModal: function (e) {
        var tarBtn = $(e.currentTarget);
        tarBtn.parents(".m-modal_bg").fadeOut(200);
    }
});

$(function () {

    new Main();

})
